Reduce

The reduce() method is a higher-order function that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value. It is necessary to make sure that operations are commutative and associative. Anonymous functions are passed as parameter to the reduce function.

Reduce function is applied on collection data structure in scala that contains lists,sequence,sets,map and tuples.Parameter in reduce function is a binary operation which merge all the elements from from the collection and returns a single value. The first two values is combined with the binary operation and the resultant of that operation combines with the next value of the collection and at last we obtain a single value.

object Demo {
   def main(args : Array[String]){
   val elements = Seq(3.5, 5.0, 1.5) 
       println(s"Given Values")
       val result=elements.reduce((x,y) => x + y)
       println( result)
  }
}

object Demo {
    def main(args : Array[String]){
    val l = List(2, 5, 3, 6, 4, 7)
    val result=l.reduce((x,y) => x max y)
    println(result)
  }
}


object Demo {
    def main(args : Array[String]){
    val collection = List(1,2,3,4,5)
    val new_collection=collection.map(x => (x,1))
    /*  List((1, 1), (2, 1), (3, 1), (4, 1), (5, 1))   */
    val res = new_collection.reduce( (a,b) => ( a._1 + b._1,a._2 + b._2 ) ) 
     println(res)
     println("Average="+ res._1/res._2.toFloat)
  }
}

Here, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained.

No comments:

Post a Comment